package top.ochiamalu.aioj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.ochiamalu.aioj.domain.entity.Favor;
import top.ochiamalu.aioj.enums.FavorTypeEnum;
import top.ochiamalu.aioj.mapper.FavorMapper;
import top.ochiamalu.aioj.service.FavorService;
import top.ochiamalu.aioj.strategy.favor.FavorStrategy;

import java.util.Map;

/**
 * 收藏服务实施
 *
 * @author ochiamalu
 * @date 2025/03/08
 */
@Service
public class FavorServiceImpl extends ServiceImpl<FavorMapper, Favor>
        implements FavorService {

    private final Map<FavorTypeEnum, FavorStrategy> strategyMap;

    public FavorServiceImpl(Map<FavorTypeEnum, FavorStrategy> strategyMap) {
        this.strategyMap = strategyMap;
    }

    /**
     * 点赞
     *
     * @param targetId 目标ID
     * @param type     点赞类型
     * @return {@link Boolean }
     */
    @Override
    public Boolean favor(Long targetId, FavorTypeEnum type) {
        long userId = StpUtil.getLoginIdAsLong();
        FavorStrategy strategy = strategyMap.get(type);

        if (strategy == null) {
            throw new RuntimeException("不支持的收藏类型: " + type);
        }

        LambdaQueryWrapper<Favor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favor::getUserId, userId);
        strategy.buildQueryCondition(queryWrapper, targetId);

        long count = this.count(queryWrapper);

        if (count > 0) {
            return this.remove(queryWrapper);
        }
        Favor favor = new Favor();
        favor.setUserId(userId);
        favor.setTargetId(targetId);
        favor.setType(type.getValue());
        return this.save(favor);
    }
}
